package com.application.lucky.manager;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.application.lucky.activity.GroupActivity;
import com.application.lucky.bean.eventbean.GroupUnreadEvent;
import com.application.lucky.bean.eventbean.MessageEvent;
import com.application.lucky.bean.jsonBean.BaseWebBean;
import com.application.lucky.bean.jsonBean.GroupListbean;
import com.application.lucky.bean.jsonBean.HandBean;
import com.application.lucky.bean.jsonBean.RedPListbean;
import com.application.lucky.bean.jsonBean.WebBean;
import com.application.lucky.bean.jsonBean.WebHeartbean;
import com.application.lucky.bean.jsonBean.WebMessageBean;
import com.application.lucky.bean.jsonBean.WebUserbean;
import com.application.lucky.request.nav.UrlManager;
import com.application.lucky.utils.JsonParserUtil;
import com.application.mylibrary.utils.EventBusUtils;
import com.application.mylibrary.utils.LogUtils;
import com.google.gson.Gson;
import com.zhangke.websocket.SimpleListener;
import com.zhangke.websocket.SocketListener;
import com.zhangke.websocket.WebSocketHandler;
import com.zhangke.websocket.WebSocketManager;
import com.zhangke.websocket.WebSocketSetting;
import com.zhangke.websocket.response.ErrorResponse;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class SocketListenerManager {
    private HashMap<String, List<RedPListbean>> messageMap = new HashMap<>();
    private HashMap<String, Integer> unreadCount = new HashMap<>();
    private HashMap<String, Boolean> getHistopy = new HashMap<>();
    private WebSocketManager manager;

    private SocketListenerManager() {
        WebSocketSetting setting = new WebSocketSetting();
        //连接地址，必填，例如 wss://echo.websocket.org
        setting.setConnectUrl(UrlManager.getws());//必填

        //设置连接超时时间
        setting.setConnectTimeout(15 * 1000);

        //设置心跳间隔时间
        setting.setConnectionLostTimeout(30);

        //设置断开后的重连次数，可以设置的很大，不会有什么性能上的影响
        setting.setReconnectFrequency(60);

        //网络状态发生变化后是否重连，
        //需要调用 WebSocketHandler.registerNetworkChangedReceiver(context) 方法注册网络监听广播
        setting.setReconnectWithNetworkChanged(true);

        //通过 init 方法初始化默认的 WebSocketManager 对象
        manager = WebSocketHandler.init(setting);

    }

    public WebSocketManager getManager() {
        return manager;
    }

    public void setManager(WebSocketManager manager) {
        this.manager = manager;
    }

    public List<RedPListbean> getMessage(String id) {
        List<RedPListbean> webMessageBeans = messageMap.get(id);
        if (webMessageBeans == null) {
            webMessageBeans = new ArrayList<>();
            messageMap.put(id, webMessageBeans);
        }
        return webMessageBeans;
    }

    public void addGroup(String groupId, RedPListbean messageBean) {

        List<RedPListbean> webMessageBeans = messageMap.get(groupId);
        if (webMessageBeans == null) {
            webMessageBeans = new ArrayList<>();
            messageMap.put(groupId, webMessageBeans);
        }
        webMessageBeans.add(messageBean);

    }

    public void clear() {

        unreadCount.clear();
        messageMap.clear();
        getHistopy.clear();
    }

    public void clear(String groupId) {
        List<GroupListbean> dataInfo = GroupDataManager.getInstance().getDataInfo();
        if (dataInfo != null) {
            for (GroupListbean groupListbean : dataInfo) {
                if (groupId.equals(groupListbean.getRoomTypeId())) {
                    dataInfo.remove(groupListbean);
                }
            }
        }
        unreadCount.remove(groupId);
        messageMap.remove(groupId);
        getHistopy.remove(groupId);
        EventBusUtils.post(new GroupUnreadEvent(groupId, 0));
    }


    private static class InnerCLass {
        private static SocketListenerManager socketListenerManager = new SocketListenerManager();
    }

    public static SocketListenerManager getInstance() {
        return InnerCLass.socketListenerManager;
    }

    public SocketListener getSocketListener() {

        return socketListener;
    }

    public void sendMessage(String command, BaseWebBean b) {
        WebBean<BaseWebBean> handBeanWebBean = new WebBean<>();
        handBeanWebBean.data = b;
        handBeanWebBean.command = command;
        String s = JSON.toJSONString(handBeanWebBean);
        LogUtils.i("lucky_log  sendMessage(String, T):" + s);
        WebSocketHandler.getDefault().send(s);
    }

    private SocketListener socketListener = new SimpleListener() {
        @Override
        public void onConnected() {

            LogUtils.i("lucky_log  onConnected");
            HandBean handBean = new HandBean();
            handBean.id = UserManagers.getInstance().getUserId();
            handBean.version = "1";
            handBean.id = UserManagers.getInstance().getUserId();

            sendMessage("0", handBean);
        }

        @Override
        public void onConnectFailed(Throwable e) {
            if (e != null) {
                LogUtils.i("lucky_log  onConnectFailed:" + e.toString());
            } else {
                LogUtils.i("lucky_log  onConnectFailed:null");
            }
        }

        @Override
        public void onDisconnect() {
            LogUtils.i("lucky_log  onDisconnect");
        }

        @Override
        public void onSendDataError(ErrorResponse errorResponse) {
            LogUtils.i("lucky_log  onSendDataError:" + errorResponse.toString());
            errorResponse.release();
        }

        @Override
        public <T> void onMessage(String message, T dd) {
            String userId = UserManagers.getInstance().getUserId();
            LogUtils.i("lucky_log  onMessage(String, T):" + message);
            JSONObject object = JSON.parseObject(message);
            String data = object.getString("data");
            String command = object.getString("command");
            switch (command) {
                case "1"://握手成功  需要绑定用户信息
                    //String id, String appId, String clientType, String token
                case "401":
                case "201":
                    sendMessage("100", new WebUserbean(userId, "1", "200", userId));
                    break;

                case "2"://心跳

                    sendMessage("3", JsonParserUtil.getBean(data, WebHeartbean.class));
                    break;
                case "101"://绑定用户之后需要进入房间
                    EventBusUtils.post(new MessageEvent(message));
                    break;
                case "204":
                    String s = object.getJSONObject("data").getString("body");
                    WebMessageBean webMessageBean = new Gson().fromJson(s, WebMessageBean.class);
                    MessageEvent messageEvent = new MessageEvent(message);
                    messageEvent.webMessageBean = webMessageBean;
//                    messageEvent.groupId =
                    RedPListbean listbean = new Gson().fromJson(webMessageBean.message, RedPListbean.class);
                    SocketListenerManager.getInstance().addGroup(webMessageBean.groupId, listbean);
                    EventBusUtils.post(messageEvent);
                    if (!GroupActivity.isSHow) {
                        setUnreadCount(webMessageBean.groupId);
                    }
                    break;
                case "205":

                    String ss = object.getJSONObject("data").getString("datas");

                    Gson gson = new Gson();//创建Gson对象
                    List<String> strings = JSON.parseArray(ss, String.class);
                    ArrayList<WebMessageBean> beans = new ArrayList<>();
                    for (String string : strings) {
                        WebMessageBean bean1 = gson.fromJson(string, WebMessageBean.class);//解析¬
                        beans.add(bean1);
                    }
                    MessageEvent messageEvent1 = new MessageEvent(message);
                    messageEvent1.webMessageBeans = beans;
                    EventBusUtils.post(messageEvent1);

            }
        }


        @Override
        public <T> void onMessage(ByteBuffer bytes, T data) {
            LogUtils.i("lucky_log  onMessage(ByteBuffer, T):" + bytes);
        }
    };

    public void setLoadHIstory(String id) {
        getHistopy.put(id, true);
    }

    public boolean getLoadHIstory(String id) {
        Boolean aBoolean = getHistopy.get(id);

        if (aBoolean == null) {
            return false;
        }

        return aBoolean;
    }


    public void setUnreadCount(String group) {
        Integer integer = unreadCount.get(group);
        if (integer == null) {
            integer = 0;
        }
        integer++;
        setUnreadCount(group, integer);


    }

    public void setUnreadCount(String group, int count) {

        unreadCount.put(group, count);
        EventBusUtils.post(new GroupUnreadEvent(group, count));

    }

    public int getUnreadCOunt() {
        int count = 0;
        Set<String> strings = unreadCount.keySet();
        for (String string : strings) {
            Integer integer = unreadCount.get(string);
            if (integer == null) {
                count += 0;
            } else {
                count += integer;
            }

        }
        return count;
    }

    public int getUnreadCOunt(String id) {
        Integer integer = unreadCount.get(id);
        if (integer == null) {
            integer = 0;
        }

        return integer;
    }

    public void clearUnRead(String groupId) {
        EventBusUtils.post(new GroupUnreadEvent(groupId, 0));
        unreadCount.put(groupId, 0);
    }
}
